package cn.wolfcode.wolf2w.strategy.service.impl;

import cn.wolfcode.wolf2w.common.core.constant.SecurityConstants;
import cn.wolfcode.wolf2w.common.core.domain.R;
import cn.wolfcode.wolf2w.common.security.utils.SecurityUtils;
import cn.wolfcode.wolf2w.member.api.RemoteUserInfoService;
import cn.wolfcode.wolf2w.member.api.domain.UserInfo;
import cn.wolfcode.wolf2w.strategy.api.domain.StrategyComment;
import cn.wolfcode.wolf2w.strategy.mapper.StrategyCommentMapper;
import cn.wolfcode.wolf2w.strategy.query.StrategyCommentQuery;
import cn.wolfcode.wolf2w.strategy.service.IStrategyCommentService;
import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 攻略评论Service业务层处理
 * 
 * @author dalang
 * @date 2023-11-27
 */
@Service
@Transactional
public class StrategyCommentServiceImpl extends ServiceImpl<StrategyCommentMapper,StrategyComment> implements IStrategyCommentService {
    @Autowired
    private RemoteUserInfoService remoteUserInfoService;

    @Override
    public IPage<StrategyComment> queryPage(StrategyCommentQuery qo) {
        IPage<StrategyComment> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        lambdaQuery()
                .eq(qo.getStrategyId()!=null,StrategyComment::getStrategyId,qo.getStrategyId())
                .page(page);

        for (StrategyComment record : page.getRecords()) {
            R<UserInfo> ret = remoteUserInfoService.getOne(record.getUserId(), SecurityConstants.INNER);
            if (ret!=null&& R.isSuccess(ret)) {
                record.setUser(ret.getData());
            }
        }
        return page;
    }

    @Override
    public boolean thumbsup(Long cid) {
        StrategyComment comment = super.getById(cid);
        List<Long> ids = comment.getThumbupidsList();
        Long uid = SecurityUtils.getUserId();
        if (ids.contains(uid)) {
            // 取消点赞
            comment.setThumbnum(comment.getThumbnum()-1);
            ids.remove(uid);
        }else{
            // 点赞
            comment.setThumbnum(comment.getThumbnum()+1);
            ids.add(uid);
        }
//        ids.stream().map(String::valueOf).collect(Collectors.joining(","));
        comment.setThumbupids(StringUtils.join(ids,","));
        super.updateById(comment);
        return ids.contains(uid);
    }
}
